package com.mux.util.http;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mux.util.common.CommUtil;



public class HttpClientUtil {
	private static final Logger logger=LoggerFactory.getLogger(HttpClientUtil.class);
	
	private static ResourceBundle bundle = ResourceBundle.getBundle("publicconfig/interfaceUrl");
	public static  ResponseInfo sendRequestGet(String urlKey,String paramStr) throws Exception{
		
		String url = bundle.getString(urlKey);
		if(StringUtils.isBlank(url)){
			logger.info("key "+urlKey+" not exists");
			return null;
		}
		
		/***/
		Map<String,String> resMap =  CommUtil.getRequestStr(url);
		
		String user = bundle.getString("user");
		String pwd = bundle.getString("pwd");
		System.out.println(user+"..."+pwd);
		//
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
               // new AuthScope("sfadev.cccil.com.cn", 8100),
        		 new AuthScope(resMap.get("host"),Integer.parseInt(resMap.get("port"))),
                new UsernamePasswordCredentials(user, pwd));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
		if(!StringUtils.isBlank(paramStr)){
			url = url.concat(paramStr);
		}
		
		
		ResponseInfo responseInfo = new ResponseInfo();
		CloseableHttpResponse 	response1 = null;
		try {
			//url = URLEncoder.encode(url,"UTF-8");
			logger.info("request url "+url);
			HttpGet httpGet = new HttpGet(url);
//			httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
			System.out.println("Executing request " + httpGet.getRequestLine());
			response1 = httpclient.execute(httpGet);
			
		   responseInfo.setStatusCode(String.valueOf(response1.getStatusLine().getStatusCode()));
		   HttpEntity entity1 = response1.getEntity();
		   responseInfo.setResponseContent(EntityUtils.toString(entity1,"UTF-8"));
		  
		   EntityUtils.consume(entity1);
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(response1!=null){
				response1.close();
			}
		}
		 return responseInfo;
	}
	
	
	/**
	 * post  方式  发送数据 key:value  形式
	 * @param url  
	 * @param map  key：value 
	 * @return
	 * @throws Exception
	 */
	public static ResponseInfo sendRequestPost(String url,Map<String,Object> map) throws Exception{
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	//	nvps.add(new BasicNameValuePair("digest", "4c2993265bc821e18c6fc79dfaa9a309e2f7d0eafa7f53cdbcd5745711feb07f"));
		//nvps.add(new BasicNameValuePair("password", "secret"));
		if(map!=null && !map.isEmpty()){
			Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
			while (it.hasNext()) {
				   Map.Entry<String,Object> entry = it.next();
				//   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
				   nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()==null?"":entry.getValue().toString()));
				  }
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		ResponseInfo responseInfo = new ResponseInfo();
		try {

		   responseInfo.setStatusCode(String.valueOf(response2.getStatusLine().getStatusCode()));
		   HttpEntity entity1 = response2.getEntity();
		   responseInfo.setResponseContent(EntityUtils.toString(entity1));
			  
		} finally {
		    response2.close();
		}
		return null;
		
	}
	
	
	/**
	 * 以流的形式发送数据
	 * @param url
	 * @param json  发送的json 串
	 * @return
	 * @throws Exception
	 */
	public static ResponseInfo sendRequestPost(String key,String json) throws Exception{
		//CloseableHttpClient httpclient = HttpClients.createDefault();
		
		String url = bundle.getString(key);
		if(StringUtils.isBlank(url)){
			logger.info("key "+key+" not exists");
			return null;
		}
		/***/
		Map<String,String> resMap =  CommUtil.getRequestStr(url);
		
		String user = bundle.getString("user");
		String pwd = bundle.getString("pwd");
		System.out.println("user:"+user+"..Password:"+pwd);
		
		//
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
              //  new AuthScope("https://sfadev.cccil.com.cn:8180", 80),
               // new AuthScope("sfadev.cccil.com.cn", 8100),
        		 new AuthScope(resMap.get("host"),Integer.parseInt(resMap.get("port"))),
                new UsernamePasswordCredentials(user, pwd));
        
      //  LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .setRetryHandler(new CustomerRequestRetryHandler())
                .build();
		
		/****/
        
      
      //设置代理服务器的ip地址和端口     
		
		
		//拼接digest
	/*	String digest = bundle.getString(Constants.REQUEST_KEYT);
		if(StringUtils.isNotBlank(digest)){
			url += "?".concat(Constants.REQUEST_KEYT).concat("=").concat(digest);
		}*/
		
		HttpPost httpPost = new HttpPost(url);
		logger.info(" request url "+url);
	//	List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		
		
		httpPost.setHeader("Content-Type","application/json");
		//以流的形式发送数据
		StringEntity entity = new StringEntity(json,Charset.forName("UTF-8"));
        entity.setContentEncoding( "UTF-8" );
        entity.setContentType( "application/json" );//设置为 json数据
		httpPost.setEntity(entity);
		
		
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		
		ResponseInfo responseInfo = new ResponseInfo();
		try {
			
		   String statusCode = String.valueOf(response2.getStatusLine().getStatusCode());
		   responseInfo.setStatusCode(statusCode);
		   HttpEntity entity1 = response2.getEntity();
		   
		   String resStr = EntityUtils.toString(entity1);
		   logger.info("request url[ "+url+"] ..status code["+statusCode+"] response data["+resStr+"]");
		   responseInfo.setResponseContent(resStr);
		   
		   EntityUtils.consume(entity1);
		   return responseInfo;
		}catch(Exception e){
			logger.info("request "+url,e);
			throw new RuntimeException(e);
		}
		finally {
			if(response2!=null){
				response2.close();
			}
		}
		
	}

}
